//
//  TransferViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/8/27.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//
// TODO: to deal with transfer between different currency
//

#import "TransferViewController.h"

@interface TransferViewController ()

@end

@implementation TransferViewController

@synthesize transaction;
@synthesize accountFromPicker;
@synthesize accountToPicker;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.delegate = self;
        transaction = nil;
        transferTransactions = [[NSMutableArray alloc] init];
        
        [self initDatePicker];
        [self initTransPropertyPicker:RootCategoryTransfer];
        [self initInputToolbar:RichInputToolbarButtonBack | RichInputToolbarButtonNext | RichInputToolbarButtonDone];
        
        categoryPicker = [[CategoryViewController alloc] initWithStyle:UITableViewStylePlain];
        categoryPicker.mode = RichTableModeListReadonly;
        categoryPicker.level = 1;
        categoryPicker.parentCode = RootCategoryTransfer;
        categoryPicker.callerDelegate = self;
        categoryPicker.navigator = self.navigator;
        
        accountFromPicker = [[AccountViewController alloc] initWithStyle:UITableViewStylePlain];
        accountFromPicker.mode = RichTableModeListReadonly;
        accountFromPicker.callerDelegate = self;
        
        accountToPicker = [[AccountViewController alloc] initWithStyle:UITableViewStylePlain];
        accountToPicker.mode = RichTableModeListReadonly;
        accountToPicker.callerDelegate = self;
        // TODO: load specified account only
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.mode == RichTableModeUpdate) {
        [[RichDelegate core] loadGeneralTransactions:transferTransactions
                                            category:RootCategoryTransfer
                                               where:[NSString stringWithFormat:@"id_pk = %lld", transaction.transId]
                                        beginAtIndex:(self.page * ROWS_PER_PAGE)
                                               limit:ROWS_PER_PAGE
                                          descending:NO];
        
        self.transaction = (RichTransactionGeneral *)[[RichDelegate core] findTransactionIn:transferTransactions byID:transaction.transId type:kTransactionTypeGeneral];
    }
    else if (self.mode == RichTableModeListEditable || self.mode == RichTableModeListReadonly) {
        [[RichDelegate core] loadGeneralTransactions:transferTransactions
                                            category:RootCategoryTransfer
                                               where:@"date <= datetime('now', 'localtime')"
                                        beginAtIndex:(self.page * ROWS_PER_PAGE)
                                               limit:ROWS_PER_PAGE
                                          descending:YES];
        
        if ([transferTransactions count] > 0)
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
        else
            self.navigationItem.rightBarButtonItem = nil;
    }
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.mode == RichTableModeCreate || self.mode == RichTableModeUpdate)
        return 8;
    else
        return [transferTransactions count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *code;
    UITableViewCell *cell = nil;
    RichTableViewTextfieldCell *textfieldCell = nil;
    
    if (self.mode == RichTableModeCreate || self.mode == RichTableModeUpdate) {
        tableCellStyle = RichTableCellStyleTextfield;
        textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        cell = textfieldCell;
        
        switch ([indexPath row]) {
            case 0:
                textfieldCell.textLabel.text = RichLocaleString(@"Date");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDefault;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.autocorrectionType = UITextAutocorrectionTypeNo;
                textfieldCell.textfield.autocapitalizationType = UITextAutocapitalizationTypeWords;
                textfieldCell.textfield.inputView = datePicker;
                
                if (self.mode == RichTableModeUpdate)
                    textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:transaction.date format:@"yyyy-MM-dd"];
                else
                    textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
                break;
                
            case 1:
                textfieldCell.textLabel.text = RichLocaleString(@"Category");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = categoryPicker.view;
                textfieldCell.textfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:transaction.categoryCode]];
                break;
                
            case 2:
                textfieldCell.textLabel.text = RichLocaleString(@"Account From");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = accountFromPicker.view;
                textfieldCell.textfield.text = [[[RichDelegate core] accounts:accounts findAccountByID:transaction.accountFrom] name];
                break;
                
            case 3:
                textfieldCell.textLabel.text = RichLocaleString(@"Account To");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = accountToPicker.view;
                textfieldCell.textfield.text = [[[RichDelegate core] accounts:accounts findAccountByID:transaction.accountTo] name];
                break;
                
            case 4:
                code = [[[RichDelegate core] accounts:accounts findAccountByID:transaction.accountFrom] currencyCode];
                textfieldCell.textLabel.text = RichLocaleString(@"Amount");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:code], transaction.amount];
                break;
            
            case 5:
                textfieldCell.textLabel.text = RichLocaleString(@"Property");
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.inputView = transPropertyPicker;
                textfieldCell.textfield.text = [[RichDelegate core] stringFromTransactionProperty:transaction.property];
                break;
                
            case 6:
                code = [[[RichDelegate core] accounts:accounts findAccountByID:transaction.accountFrom] currencyCode];
                textfieldCell.textLabel.text = RichLocaleString(@"Commission");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDecimalPad;
                textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                textfieldCell.textfield.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:code], transaction.commission];
                break;
                
            case 7:
                textfieldCell.textLabel.text = RichLocaleString(@"Comment");
                textfieldCell.textfield.keyboardType = UIKeyboardTypeDefault;
                textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                textfieldCell.textfield.text = transaction.comment;
                break;
        }
    }
    else if (self.mode == RichTableModeListEditable) {
        tableCellStyle = RichTableCellStyleValue;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        RichTransactionGeneral *trans = nil;
        
        if (transferTransactions > 0)
            trans = [transferTransactions objectAtIndex:[indexPath row]];
        
        if (trans) {
            code = [[[RichDelegate core] accounts:accounts findAccountByID:trans.accountFrom] currencyCode];
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",
                                   [[RichDelegate core] stringFromDate:trans.date format:@"MM/dd"],
                                   [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:trans.categoryCode]]];
            
            cell.detailTextLabel.text = [[RichDelegate core] currencyFormatWithSign:trans.amount code:code];
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.userInteractionEnabled = YES;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        RichTransactionGeneral *trans = [transferTransactions objectAtIndex:[indexPath row]];
        uint64_t transId = trans.transId;
        
        [[RichDelegate core] deleteTransaction:transId type:kTransactionTypeGeneral];
        
        [transferTransactions removeObject:trans];
        
        if ([transferTransactions count] > 0)
            self.navigationItem.rightBarButtonItem = self.editButtonItem;
        else {
            self.navigationItem.rightBarButtonItem = nil;
            [self setEditing:NO];
        }
        
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.editing)
        return UITableViewCellEditingStyleDelete;
    else
        return UITableViewCellEditingStyleNone;
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    if (tableView.tag == RichTableViewTagCategory) {
    /*
     * Called by CategoryViewController
     */
        
        currentTextfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:categoryPicker.currentCode]];
    }
    else if (tableView.tag == RichTableViewTagAccount) {
        /*
         * Called by AccountViewController
         */
        
        if (currentTextfield.tag == 2)
            currentTextfield.text = accountFromPicker.account.name;
        else if (currentTextfield.tag == 3)
            currentTextfield.text = accountToPicker.account.name;
    }
    else {
        /*
         * Called by self
         */
        if (self.mode == RichTableModeListEditable) {
            if (self.mode != RichTableModeUpdate) {
                TransferViewController *tvc = [[TransferViewController alloc] initWithStyle:UITableViewStylePlain];
                tvc.transaction = [transferTransactions objectAtIndex:[indexPath row]];
                tvc.mode = RichTableModeUpdate;
                tvc.navigator = self.navigator;
                [self.navigator pushViewController:tvc animated:YES];
                [tvc release];
            }
        }
    }
}

#pragma mark - Toolbar button actions

- (void)toolbarDidPressBackButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 1) {
        /* Category */
        [[NSNotificationCenter defaultCenter] postNotificationName:@"CategoryNotificationBackToUpperLevel" object:nil];
    }
    
    [super toolbarDidPressBackButton:sender];
}

- (void)toolbarDidPressNextButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 0) {
        /* Date */
        currentTextfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
    }
    else if (currentTextfield.tag == 1) {
        /* Category */
        if (categoryPicker.currentCode > 0) {
            currentTextfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:categoryPicker.currentCode]];
            categoryPicker.level = 1;
            categoryPicker.parentCode = RootCategoryTransfer;
        }
    }
    else if (currentTextfield.tag == 2) {
        /* Account From */
        if (accountFromPicker.account)
            currentTextfield.text = accountFromPicker.account.name;
    }
    else if (currentTextfield.tag == 2) {
    /* Account To */
        if (accountToPicker.account)
            currentTextfield.text = accountToPicker.account.name;
    }
    
    [super toolbarDidPressNextButton:sender];
}

- (void)toolbarDidPressDoneButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 0)
        currentTextfield.text = [[RichDelegate core] stringFromDate:datePicker.date format:@"yyyy-MM-dd"];
    else if (currentTextfield.tag == 1) {
        if (categoryPicker.currentCode > 0) {
            currentTextfield.text = [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:categoryPicker.currentCode]];
            categoryPicker.level = 1;
            categoryPicker.parentCode = RootCategoryTransfer;
        }
    }
    else if (currentTextfield.tag == 2) {
        if (accountFromPicker.account)
            currentTextfield.text = accountFromPicker.account.name;
    }
    else if (currentTextfield.tag == 3) {
        if (accountToPicker.account)
            currentTextfield.text = accountToPicker.account.name;
    }
    
    [super toolbarDidPressDoneButton:sender];
}

#pragma mark - Textfield delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    if (self.mode == RichTableModeUpdate)
        if (textField.tag == 0)
            datePicker.date = transaction.date;
    
    if (textField.tag == 4 || textField.tag == 6)
        if ([textField.text isEqualToString:@"0"])
            textField.text = @"";
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [super textFieldDidEndEditing:textField];
    
    if (transaction == nil) {
        transaction = [[RichTransactionGeneral alloc] init];
        transaction.date = datePicker.date;
        transaction.accountFrom = 0;
        transaction.accountTo = 0;
    }
    
    switch (textField.tag) {
        case 0:
            transaction.date = datePicker.date;
            break;
        case 1:
            if (categoryPicker.currentCode)
                transaction.categoryCode = categoryPicker.currentCode;
            break;
        case 2:
            if (accountFromPicker.account.accountId)
                transaction.accountFrom = accountFromPicker.account.accountId;
            break;
        case 3:
            if (accountToPicker.account.accountId)
                transaction.accountTo = accountToPicker.account.accountId;
            break;
        case 4:
            if ([textField.text isEqualToString:@""])
                textField.text = @"0";
            
            transaction.amount = [textField.text floatValue];
            
            break;
        case 5:
            break;
        case 6:
            if ([textField.text isEqualToString:@""])
                textField.text = @"0";
            
            transaction.commission = [textField.text floatValue];
            
            break;
        case 7:
            transaction.comment = textField.text;
            break;
    }
}

#pragma mark - Picker view delegate and datasource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)tableComponents
{
    [super pickerView:pickerView didSelectRow:row inComponent:tableComponents];
    
    transaction.property = row + TransactionPropertyTransferNone;
}

#pragma mark - RichTableViewController Delegate

- (void)didPressCreate
{
    TransferViewController *tvc = [[TransferViewController alloc] initWithStyle:UITableViewStylePlain];
    tvc.mode = RichTableModeCreate;
    tvc.navigator = self.navigator;
    [self.navigator pushViewController:tvc animated:YES];
    [tvc release];
}

- (void)didPressCreateDone
{
    if ([[RichDelegate core] createTransaction:(id *)transaction type:kTransactionTypeGeneral] <= 0) {
        NSLog(@"Create transaction failed");
        
        // TODO: [General Transaction] create transaction error handling
    }
    else {
        [transferTransactions addObject:transaction];
        self.navigationItem.rightBarButtonItem = self.editButtonItem;
    }
    
    [transaction release];
    transaction = nil;
    
    [self.navigator popViewControllerAnimated:YES];
}

- (void)didPressUpdateDone
{
    if ([[RichDelegate core] updateTransaction:(id *)transaction type:kTransactionTypeGeneral] < 0) {
        NSLog(@"Update transaction failed");
        
        // TODO: [General Transaction] update transaction error handling
    }
    
    [transaction release];
    transaction = nil;
    
    [self.navigator popViewControllerAnimated:YES];
}

@end
